import { ArgumentsHost, Catch, ExceptionFilter, HttpException } from '@nestjs/common'
import { FastifyReply } from 'fastify'
import { returnPack } from '../contants/config.contants'
import { HttpCodeMap } from '../contants/http-code.contants'

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp()
    const response = ctx.getResponse<FastifyReply>()
    const status = exception.getStatus()



    // const msg = HttpCodeMap[status] ?? exception.getResponse()['message'] ?? exception.message
    const msg = HttpCodeMap[status] ??
      (typeof response === 'string'
        ? response
        : response && typeof response === 'object' && 'message' in response
          ? (response as any)['message']  // 或用 HttpExceptionResponse 类型
          : null)
      ?? exception.message
      ?? '默认错误消息'

    const errorResponse = returnPack({
      data: {},
      code: -1,
      msg
    })

    // Fastify API：用 .send() 替换 .json()
    response
      .status(status)
      .header('Content-Type', 'application/json; charset=utf-8')  // 可选，默认已 JSON
      .send(errorResponse)  // send() 自动处理 JSON 对象
  }
}
